package service

import (
	"dataaysn/internal/model"
	"dataaysn/internal/repository"

	"strconv"

	"github.com/gin-gonic/gin"
)

type DataSourceService struct {
	repo repository.DataSourceRepository
}

func NewDataSourceService(repo repository.DataSourceRepository) *DataSourceService {
	return &DataSourceService{repo: repo}
}

func (s *DataSourceService) CreateDataSource(c *gin.Context) {
	var ds model.DataSource
	if err := c.ShouldBindJSON(&ds); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	if err := s.repo.CreateDataSource(&ds); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}

	c.JSON(200, ds)
}

func (s *DataSourceService) GetDataSource(c *gin.Context) {
	id := c.Param("id")
	ds, err := s.repo.GetDataSource(id)
	if err != nil {
		c.JSON(404, gin.H{"error": "not found"})
		return
	}
	c.JSON(200, ds)
}

func (s *DataSourceService) UpdateDataSource(c *gin.Context) {
	id := c.Param("id")
	var ds model.DataSource
	if err := c.ShouldBindJSON(&ds); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	uintID, err := strconv.ParseUint(id, 10, 32)
	if err != nil {
		// 转换失败，返回错误响应
		c.JSON(400, gin.H{"error": "invalid id format"})
		return
	}
	ds.ID = uint(uintID)
	if err := s.repo.UpdateDataSource(&ds); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}

	c.JSON(200, ds)
}

func (s *DataSourceService) DeleteDataSource(c *gin.Context) {
	id := c.Param("id")
	if err := s.repo.DeleteDataSource(id); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, gin.H{"message": "deleted"})
}

func (s *DataSourceService) ListDataSources(c *gin.Context) {
	dss, err := s.repo.ListDataSources()
	if err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, dss)
}

func (s *DataSourceService) TestConnection(c *gin.Context) {
	var ds model.DataSource
	if err := c.ShouldBindJSON(&ds); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	if err := s.repo.TestDataSourceConnection(&ds); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}

	c.JSON(200, gin.H{"message": "connection successful"})
}
